﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.IO;

namespace HRDexCapstoneProject.DocumentManagement
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        string sqlc;
        SqlConnection conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\HRdexDB.mdf;Integrated Security=True;User Instance=True");
        protected void Page_Load(object sender, EventArgs e)
        {
            //string hrdoc = (string)(Session["hrdoc"]);
            //if (hrdoc == "1")
            //{
            //    gvFiles.Columns[6].Visible = true;
            //}
        }

        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            //this.cmdStore.Click += new System.EventHandler(this.cmdStore_Click);
            this.Load += new System.EventHandler(this.Page_Load);
        }

        void sqlexecute(string sqlcmd)
        {
            SqlCommand cmd = new SqlCommand(sqlcmd,conn);
            try
            {
                conn.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                conn.Close();
            }
            
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            string filepath = upldrFiles.PostedFile.FileName;
            if (filepath.Length != 0)
            {
                string filename = Path.GetFileName(filepath);
                string contenttype = Path.GetExtension(filepath);

                Stream fs = upldrFiles.PostedFile.InputStream;
                BinaryReader br = new BinaryReader(fs);
                Byte[] bytes = br.ReadBytes((Int32)fs.Length);

                sqlc = "INSERT INTO formFile (FolderID, FileName, FileType, FileData, EmployeesID)" +
                    "VALUES ( " + Session["pfolder"] +
                    " , " + filename +
                    " , " + contenttype +
                    " , " + bytes +
                    " , " + (string)(Session["EmployeeID"]) + ")";
                sqlexecute(sqlc);
            }
            
        }

        protected void gvFiles_SelectedIndexChanged(object sender, EventArgs e)
        {
            string strQuery = "SELECT FileName, FileType, FileData FROM formFile WHERE FileID = " + gvFiles.SelectedDataKey.Value.ToString();
            SqlCommand cmd = new SqlCommand(strQuery);
            DataTable dt = GetData(cmd);
            if (dt != null)
            {
                download(dt);
            }
        }

        private DataTable GetData(SqlCommand cmd)
        {
            DataTable dt = new DataTable();
            SqlDataAdapter sda = new SqlDataAdapter();
            cmd.CommandType = CommandType.Text;
            cmd.Connection = conn;
            try
            {
                conn.Open();
                sda.SelectCommand = cmd;
                sda.Fill(dt);
                return dt;

            }
            catch
            {
                return null;
            }
            finally
            {
                conn.Close();
                sda.Dispose();
                conn.Dispose();
            }

        }
        private void download(DataTable dt)
        {
            Byte[] bytes = (Byte[])dt.Rows[0]["FileData"];
            Response.Buffer = true;
            Response.Charset = "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = dt.Rows[0]["FileType"].ToString();
            Response.AddHeader("content-disposition", "attachment;FileName="
            + dt.Rows[0]["FileName"].ToString());
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            dsFiles.SelectCommand = "SELECT formFile.FileID, formFile.FileName, formFile.FileType, " + 
                "formFolder.FolderName, formEmployees.LastName + ', ' + formEmployees.FirstName AS fulName " + 
                "FROM formFile INNER JOIN formFolder ON formFile.FolderID = formFolder.FolderID INNER JOIN " + 
                "formEmployees ON formFile.EmployeesID = formEmployees.EmployeesID WHERE (formFile.FileName LIKE '" +
                txtnfName.Text + "' + '%')";
        }

        protected void gvFiles_RowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            //sqlc = "DELETE FROM formFile WHERE FileID = " + gvFiles.SelectedDataKey.Value.ToString();
            //sqlexecute(sqlc);
        }

        
        
    }
}